<template>
  <div class="file-upload">
    <a-upload-dragger :file-list="fileList" :before-upload="beforeUpload" :custom-request="customUpload" :multiple="true" :show-upload-list="false" accept="*/*" class="upload-dragger">
      <p class="ant-upload-drag-icon">
        <cloud-upload-outlined />
      </p>
      <p class="ant-upload-text">点击或拖拽文件到此区域上传</p>
      <p class="ant-upload-hint">支持单个或批量上传，文件大小不超过{{ maxFileSizeMB }}MB</p>
    </a-upload-dragger>

    <!-- 上传进度列表 -->
    <div v-if="uploadList.length > 0" class="upload-list">
      <div class="upload-list-header">
        <span>上传进度</span>
        <a-button type="text" size="small" @click="clearUploadList">
          <template #icon><clear-outlined /></template>
          清空
        </a-button>
      </div>
      <div class="upload-items">
        <div v-for="item in uploadList" :key="item.uid" class="upload-item">
          <div class="upload-item-info">
            <component :is="getFileIcon(item.file.type)" class="file-icon" />
            <div class="file-details">
              <div class="file-name">{{ item.file.name }}</div>
              <div class="file-size">{{ formatFileSize(item.file.size) }}</div>
            </div>
          </div>
          <div class="upload-item-actions">
            <a-progress v-if="item.status === 'uploading'" :percent="item.percent" size="small" :show-info="false" style="width: 100px; margin-right: 8px" />
            <a-tag v-else-if="item.status === 'success'" color="success" style="margin-right: 8px"> 成功 </a-tag>
            <a-tag v-else-if="item.status === 'error'" color="error" style="margin-right: 8px"> 失败 </a-tag>
            <a-button v-if="item.status === 'error'" type="text" size="small" @click="retryUpload(item)"> 重试 </a-button>
            <a-button type="text" size="small" @click="removeUploadItem(item.uid)">
              <template #icon><close-outlined /></template>
            </a-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 上传设置模态框 -->
    <a-modal v-model:open="uploadModalVisible" title="文件上传设置" @ok="handleUpload" @cancel="resetUploadForm" :confirm-loading="uploading">
      <a-form :model="uploadForm" :rules="uploadRules" ref="uploadFormRef" layout="vertical">
        <a-form-item label="文件分类" name="categoryId" v-if="showCategorySelection">
          <a-radio-group v-model:value="uploadForm.categoryId" button-style="solid">
            <a-radio-button v-for="category in categoryOptions" :key="category.value" :value="category.value">
              {{ category.label }}
            </a-radio-button>
          </a-radio-group>
        </a-form-item>
        <a-form-item v-else label="文件分类">
          <div style="padding: 8px 12px; background: #f0f9ff; border: 1px solid #91d5ff; border-radius: 8px; display: inline-flex; align-items: center">
            <folder-outlined style="margin-right: 6px; color: #1890ff; font-size: 16px" />
            <span style="color: #1890ff; font-weight: 500; font-size: 14px">{{ currentCategoryName }}</span>
          </div>
        </a-form-item>
        <a-form-item label="文件描述" name="description">
          <a-textarea v-model:value="uploadForm.description" placeholder="请输入文件描述（可选）" :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  CloudUploadOutlined,
  ClearOutlined,
  CloseOutlined,
  FileOutlined,
  FileImageOutlined,
  FilePdfOutlined,
  FileWordOutlined,
  FileExcelOutlined,
  FilePptOutlined,
  FileZipOutlined,
  VideoCameraOutlined,
  AudioOutlined,
  FolderOutlined
} from '@ant-design/icons-vue'
import { useFileStorageStore } from '@/stores/fileStorage'
import { useUserStore } from '@/stores/user'

// 使用store
const fileStorageStore = useFileStorageStore()
const userStore = useUserStore()

// 响应式数据
const fileList = ref([])
const uploadList = ref([])
const uploadModalVisible = ref(false)
const uploading = ref(false)
const uploadFormRef = ref()
const pendingFiles = ref([])
const maxFileSizeMB = ref(100) // 默认100MB

// 表单数据
const uploadForm = ref({
  categoryId: '',
  description: ''
})

// 表单验证规则 - 动态规则，只有在显示分类选择时才验证
const uploadRules = computed(() => ({
  categoryId: showCategorySelection.value ? [{ required: true, message: '请选择文件分类', trigger: 'change' }] : []
}))

// 计算属性
const categoryOptions = computed(() => {
  return fileStorageStore.categories
    .filter((category) => category.id !== 'all')
    .map((category) => ({
      label: category.name,
      value: category.id,
      description: category.description
    }))
})

// 是否显示分类选择（只有在全部分类时才显示）
const showCategorySelection = computed(() => {
  return fileStorageStore.selectedCategory[0] === 'all'
})

// 当前分类名称
const currentCategoryName = computed(() => {
  const currentCategory = fileStorageStore.categories.find((cat) => cat.id === fileStorageStore.selectedCategory[0])
  return currentCategory?.name || '未分类'
})

// 方法
const loadUploadSettings = async () => {
  try {
    const settings = await fileStorageStore.getUploadSettings()
    maxFileSizeMB.value = settings.maxFileSizeMB
  } catch (error) {
    console.error('加载上传设置失败:', error)
    maxFileSizeMB.value = 100 // 使用默认值
  }
}

const beforeUpload = (file) => {
  // 检查文件大小（动态限制）
  const fileSizeMB = file.size / 1024 / 1024
  if (fileSizeMB > maxFileSizeMB.value) {
    message.error(`文件大小不能超过${maxFileSizeMB.value}MB!`)
    return false
  }

  // 添加到待上传列表
  const uploadItem = {
    uid: file.uid || Date.now() + Math.random(),
    file: file,
    status: 'ready',
    percent: 0
  }

  uploadList.value.push(uploadItem)
  pendingFiles.value.push(file)

  // 如果只有一个文件，直接打开设置模态框
  if (pendingFiles.value.length === 1) {
    openUploadModal()
  }

  return false // 阻止自动上传
}

const customUpload = (options) => {
  // 这个方法不会被调用，因为我们返回了false
}

const openUploadModal = () => {
  // 如果当前不是"全部"分类，自动设置为当前分类
  if (fileStorageStore.selectedCategory[0] !== 'all') {
    uploadForm.value.categoryId = fileStorageStore.selectedCategory[0]
  } else {
    // 如果是"全部"分类，清空之前的选择
    uploadForm.value.categoryId = ''
  }
  uploadModalVisible.value = true
}

const handleUpload = async () => {
  try {
    await uploadFormRef.value.validate()

    if (pendingFiles.value.length === 0) {
      message.warning('请选择要上传的文件')
      return
    }

    uploading.value = true

    // 批量上传文件
    for (const file of pendingFiles.value) {
      await uploadSingleFile(file)
    }

    message.success(`成功上传 ${pendingFiles.value.length} 个文件`)
    resetUploadForm()

    // 刷新文件列表
    await fileStorageStore.loadFiles()
  } catch (error) {
    if (error.errorFields) {
      // 表单验证错误
      return
    }
    message.error(error.message || '上传失败')
  } finally {
    uploading.value = false
  }
}

const uploadSingleFile = async (file) => {
  const uploadItem = uploadList.value.find((item) => item.file === file)
  if (!uploadItem) return

  try {
    uploadItem.status = 'uploading'
    uploadItem.percent = 0

    // 创建FormData
    const formData = new FormData()
    formData.append('file', file)
    formData.append('categoryId', uploadForm.value.categoryId)
    formData.append('description', uploadForm.value.description || '')

    // 模拟上传进度
    const progressInterval = setInterval(() => {
      if (uploadItem.percent < 90) {
        uploadItem.percent += Math.random() * 10
      }
    }, 200)

    // 上传文件
    await fileStorageStore.uploadFileData(formData)

    clearInterval(progressInterval)
    uploadItem.status = 'success'
    uploadItem.percent = 100
  } catch (error) {
    uploadItem.status = 'error'
    uploadItem.percent = 0
    console.error('文件上传失败:', error)
  }
}

const retryUpload = async (item) => {
  await uploadSingleFile(item.file)
}

const removeUploadItem = (uid) => {
  const index = uploadList.value.findIndex((item) => item.uid === uid)
  if (index !== -1) {
    const item = uploadList.value[index]
    uploadList.value.splice(index, 1)

    // 从待上传列表中移除
    const fileIndex = pendingFiles.value.findIndex((file) => file === item.file)
    if (fileIndex !== -1) {
      pendingFiles.value.splice(fileIndex, 1)
    }
  }
}

const clearUploadList = () => {
  uploadList.value = []
  pendingFiles.value = []
}

const resetUploadForm = () => {
  uploadForm.value = {
    categoryId: '',
    description: ''
  }
  uploadFormRef.value?.resetFields()
  clearUploadList()
  uploadModalVisible.value = false
}

const getFileIcon = (mimeType) => {
  const type = mimeType?.toLowerCase() || ''

  if (type.includes('image')) {
    return FileImageOutlined
  } else if (type.includes('video')) {
    return VideoCameraOutlined
  } else if (type.includes('audio')) {
    return AudioOutlined
  } else if (type.includes('pdf')) {
    return FilePdfOutlined
  } else if (type.includes('word') || type.includes('doc')) {
    return FileWordOutlined
  } else if (type.includes('excel') || type.includes('xls')) {
    return FileExcelOutlined
  } else if (type.includes('powerpoint') || type.includes('ppt')) {
    return FilePptOutlined
  } else if (type.includes('zip') || type.includes('rar') || type.includes('7z')) {
    return FileZipOutlined
  } else {
    return FileOutlined
  }
}

const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 生命周期
onMounted(() => {
  loadUploadSettings()
})
</script>

<style scoped>
.file-upload {
  margin-bottom: 16px;
}

.upload-dragger {
  border-radius: 8px;
  background: #fafafa;
  transition: all 0.3s;
}

.upload-dragger:hover {
  border-color: #1890ff;
  background: #f0f9ff;
}

.upload-dragger .ant-upload-drag-icon {
  font-size: 48px;
  color: #1890ff;
  margin-bottom: 16px;
}

.upload-dragger .ant-upload-text {
  font-size: 16px;
  color: #262626;
  margin-bottom: 8px;
}

.upload-dragger .ant-upload-hint {
  font-size: 14px;
  color: #8c8c8c;
}

.upload-list {
  margin-top: 16px;
  background: #fff;
  border-radius: 8px;
  border: 1px solid #f0f0f0;
}

.upload-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  font-weight: 500;
  color: #262626;
}

.upload-items {
  max-height: 300px;
  overflow-y: auto;
}

.upload-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.upload-item:last-child {
  border-bottom: none;
}

.upload-item-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.file-icon {
  margin-right: 12px;
  font-size: 20px;
  color: #1890ff;
}

.file-details {
  flex: 1;
}

.file-name {
  font-size: 14px;
  color: #262626;
  margin-bottom: 4px;
  word-break: break-all;
}

.file-size {
  font-size: 12px;
  color: #8c8c8c;
}

.upload-item-actions {
  display: flex;
  align-items: center;
}

/* 滚动条样式 */
.upload-items::-webkit-scrollbar {
  width: 6px;
}

.upload-items::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.upload-items::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.upload-items::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
